package com.io.util;

import java.security.MessageDigest;
import java.util.Date;
import java.util.Random;

public class EncryptUtils {
    static final char[] Hexes = "0123456789abcdef".toCharArray();

    private static Random random = new Random((new Date()).getTime());

    public static String sha256(String value) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(value.getBytes("UTF-8"));
            return hex(md.digest());
        }
        catch (Exception ignored){
        }
        return null;
    }

    public static String randomPassword(int len){
        String pwdChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder sb = new StringBuilder(len);
        for(int i=0; i<len; i++) {
            sb.append(pwdChars.charAt(random.nextInt(pwdChars.length())));
        }
        return sb.toString();
    }

    public static String hex(byte[] raw) {
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(Hexes[(b & 0xF0) >> 4]).append(Hexes[(b & 0x0F)]);
        }
        return hex.toString();
    }
}
